package com.quasar.hpatient.view.prescription;

import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.quasar.hpatient.MainAppliaction;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseActivity;
import com.quasar.hpatient.constant.ConstantManger;
import com.quasar.hpatient.model.custommodel.AllprescriptionDataBean;
import com.quasar.hpatient.model.custommodel.RemindMedicineTableItem;
import com.quasar.hpatient.model.event.UpdateEvent;
import com.quasar.hpatient.model.httpmodel.AnotherResult;
import com.quasar.hpatient.model.httpmodel.DataStateResult;
import com.quasar.hpatient.model.litePalmodel.MedicineInfodb;
import com.quasar.hpatient.model.medicalmodel.MedicationRecordData;
import com.quasar.hpatient.model.medicalmodel.OnedayMedicationData;
import com.quasar.hpatient.model.medicalmodel.PrescriptionDayData;
import com.quasar.hpatient.onInterface.OnMedicationListener;
import com.quasar.hpatient.onInterface.OnSelectPrescriptionListener;
import com.quasar.hpatient.presenter.RemindMedicinePresenter;
import com.quasar.hpatient.presenter.SelectPrescriptionPresenter;
import com.quasar.hpatient.utils.TimeZoneUtil;
import com.quasar.hpatient.view.adapter.RemindMedicineAdapter;
import com.rey.material.app.Dialog;
import com.rey.material.app.DialogFragment;
import com.rey.material.app.SimpleDialog;
import com.vise.log.ViseLog;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.OptionsItem;
import org.androidannotations.annotations.OptionsMenu;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 服药单
 */
@OptionsMenu(R.menu.menu_add_medicine)
@EActivity(R.layout.activity_medication)
public class MedicationActivity extends BaseActivity implements OnMedicationListener,OnSelectPrescriptionListener {

    private RemindMedicineAdapter remindMedicineAdapter;
    private RemindMedicinePresenter remindMedicinePresenter;
    private SelectPrescriptionPresenter selectPrescriptionPresenter;
    //保存当前服药单信息
    List<RemindMedicineTableItem> remindMedicineTableItem;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    //时间戳转换
    long startDay;
    //当前时间的时间戳
    long newStatsDay;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    @ViewById(R.id.main_toolbar)
    Toolbar main_toolbar;
    @ViewById(R.id.pre)
    Button pre;
    @ViewById(R.id.next)
    Button next;
    @ViewById(R.id.rv_list)
    RecyclerView rv_list;
    @ViewById(R.id.iv_search_date)
    ImageView iv_search_date;
    @ViewById(R.id.date)
    TextView date;

    @AfterViews
    void init() {
        initToolbar();
        initView();
        initData();

    }

    @Override
    protected void initView() {
        date.setText(format.format(new Date()).substring(0, 10));
        rv_list.setLayoutManager(new LinearLayoutManager(this));
        pre.setVisibility(View.GONE);
        next.setVisibility(View.GONE);
    }

    @Override
    protected void initData() {

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        remindMedicinePresenter = new RemindMedicinePresenter(this);
        selectPrescriptionPresenter=new SelectPrescriptionPresenter(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //查询当日服药单信息
        showDialog();
        remindMedicinePresenter.GetPatientSingleDoseDetailData(TimeZoneUtil.sdf.format(new Date()));
        selectPrescriptionPresenter.AtPrescription();
    }

    //初始化adapter布局
    public void initAdapter(List<RemindMedicineTableItem> data) {
        remindMedicineAdapter = new RemindMedicineAdapter(data);
        rv_list.setAdapter(remindMedicineAdapter);
        //itme的点击事件
        remindMedicineAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.remind_med_name:
                        ViseLog.d("输出的药品名称" + remindMedicineAdapter.getData().get(position).getName());
                        if (remindMedicineAdapter.getData().get(position).getName() != null) {
                            msg(remindMedicineAdapter.getData().get(position).getName());
                        }
                        break;

                    case R.id.remind_stats://一种服药
                        if (remindMedicineAdapter.getData().get(position) != null) {
                            RemindMedicineTableItem remindMedicineTableItem = remindMedicineAdapter.getData().get(position);
                            if (remindMedicineTableItem != null) {
                                if(remindMedicineTableItem.getName()!=null){
                                    if (remindMedicineTableItem.getStats() == 0) {
                                        OneTakeMedicineDiaLog(position, remindMedicineTableItem);
                                    }
                                }
                            }
                        }
                        break;

                    case R.id.submit://一键服药

                        boolean onclick = false;

                        for (int i = 0; i < remindMedicineAdapter.getData().size(); i++) {
                            if (remindMedicineAdapter.getData().get(i).getName() != null) {
                                if (remindMedicineAdapter.getData().get(i).getStats() == 0) {
                                    onclick = true;
                                }
                            }
                        }

                        if (onclick) {
                            if (remindMedicineAdapter.getData().get(position) != null) {
                                oneMedicineDialog();
                            }
                        } else {
                            msg("暂无可服药物");
                        }

                        break;
                }
            }
        });

    }

    @Override
    public void onSuccess(AnotherResult<OnedayMedicationData> data) {
        remindMedicineTableItem = new ArrayList<>();
        remindMedicineTableItem.add(new RemindMedicineTableItem(RemindMedicineTableItem.HEAD));//添加标题
        for (int i = 0; i < data.getList().size(); i++) {
            RemindMedicineTableItem remindMedi = new RemindMedicineTableItem();
            remindMedi.setItemType(RemindMedicineTableItem.BODY);//布局
            remindMedi.setId(data.getList().get(i).getId());//药品id
            remindMedi.setName(data.getList().get(i).getMName());//药品名称
            remindMedi.setDose(data.getList().get(i).getDoseName());//药品剂量
            remindMedi.setSpecifications(data.getList().get(i).getUseCount()+"");//药品规格
            remindMedi.setMedicineTime(data.getList().get(i).getUseTime().substring(10, 16));//服药时间
            remindMedi.setStats(data.getList().get(i).getStatus());//服药状态
            remindMedi.setDetailId(data.getList().get(i).getDetailId());//药单id
            remindMedicineTableItem.add(remindMedi);

        }
        remindMedicineTableItem.add(new RemindMedicineTableItem(RemindMedicineTableItem.FOUR));//添加标题
        initAdapter(remindMedicineTableItem);
        dessDialog();
    }


    @Override
    public void onError(String msg) {
        if (msg != null) {
            msg(msg);
        }
        dessDialog();
    }

    @Override
    public void onRefreshUI() {
        if(remindMedicineAdapter!=null){
            remindMedicineAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onAddMutiTakeMedicine(DataStateResult dataStateResult) {
        ViseLog.d("AddOneTakeMedicine" + dataStateResult.getMsgCode());
        if (dataStateResult.getMsgCode().equals("0x00000000")) {
            //服药成功重新请求接口
            //查询当日服药单信息
            ViseLog.d("服药成功" + dataStateResult.getMsgCode());
            showDialog();
            remindMedicinePresenter.GetPatientSingleDoseDetailData(TimeZoneUtil.sdf.format(new Date()));
        }
    }

    @Override
    public void AddOneTakeMedicine(DataStateResult dataStateResult) {
        ViseLog.d("AddOneTakeMedicine" + dataStateResult.getMsgCode());
        if (dataStateResult.getMsgCode().equals("0x00000000")) {
            //服药成功重新请求接口
            //查询当日服药单信息
            ViseLog.d("服药成功" + dataStateResult.getMsgCode());
            showDialog();
            remindMedicinePresenter.GetPatientSingleDoseDetailData(TimeZoneUtil.sdf.format(new Date()));
        }
    }

    @Override
    public void onSuccessMedicationRecordDate(AnotherResult<MedicationRecordData> data) {

    }

    @Override
    public void OnSeccessLast(AnotherResult<OnedayMedicationData> data) {

    }

    @Override
    public void OnSeccessNext(AnotherResult<OnedayMedicationData> data) {

    }

    //一种服药信息
    public void OneTakeMedicineDiaLog(final int index, final RemindMedicineTableItem remindMedicineTableItem) {

        Dialog.Builder builder = new SimpleDialog.Builder(R.style.SimpleDialogLight) {
            @Override
            public void onPositiveActionClicked(DialogFragment fragment) {
                super.onPositiveActionClicked(fragment);
                //是否超时
                OneTakeMedicineInterface(Overtime(remindMedicineTableItem),index, remindMedicineTableItem);
            }

            @Override
            public void onNegativeActionClicked(DialogFragment fragment) {
                super.onNegativeActionClicked(fragment);
            }
            //按时服药
            @Override
            public void onNeutralActionClicked(DialogFragment fragment) {
                super.onNeutralActionClicked(fragment);
                OneTakeMedicineInterface(1,index, remindMedicineTableItem);
            }
        };

        StringBuffer titleMsg=new StringBuffer();
        titleMsg.append("你确定要服药了吗？");
        if(Overtime(remindMedicineTableItem)==2){
            titleMsg.append("(您已超时)");
        }
        builder.title(titleMsg.toString())
                .positiveAction("确定")
                .neutralAction("我已按时服药")
                .negativeAction("取消");
        ((SimpleDialog.Builder) builder).message("药品名称：" + remindMedicineTableItem.getName()
                + "\n药品规格：" + remindMedicineTableItem.getDose()
                + "\n本次用量：" + remindMedicineTableItem.getSpecifications()//+ "×" + recordMedicationItem.getUnit()
                + "\n提醒时间：" + remindMedicineTableItem.getMedicineTime());
        DialogFragment fragment = DialogFragment.newInstance(builder);

        if (this instanceof AppCompatActivity) {
            AppCompatActivity activity = this;
            fragment.show(activity.getSupportFragmentManager(), null);
        }
    }

    //一种服药接口调用
    public void OneTakeMedicineInterface(int index,int position, RemindMedicineTableItem remindMedicineTableItem) {
        String id = remindMedicineAdapter.getData().get(position).getId() + "";
        remindMedicinePresenter.AddOneTakeMedicineData(index + "", id,remindMedicineTableItem.getDetailId()+"",TimeZoneUtil.sdf.format(new Date()));
    }


    //判断当前服药时间是否超时
    public int  Overtime(RemindMedicineTableItem remindMedicineTableItem){

        int medicineStats = 1;//正常
        //判断服药是否超时，服药时间大于15分钟时状态为1
        StringBuffer buffer = new StringBuffer();
        buffer.append(format.format(new Date()));
        buffer.append(" " + remindMedicineTableItem.getMedicineTime());
        buffer.append(":00");
        ViseLog.d("转换后的时间" + buffer.toString());
        //计划时间
        startDay = TimeZoneUtil.getStringToDate(buffer.toString(), "yyyy-MM-dd HH:mm:ss");
        //实际时间
        newStatsDay = TimeZoneUtil.getStringToDate(sdf.format(new Date()), "yyyy-MM-dd HH:mm:ss");
        if ((newStatsDay-startDay) > 15*60*1000) {
            medicineStats = 2;
        }
        ViseLog.d("状态"+medicineStats);
        return medicineStats;
    }


    //一键服药dialog
    public void oneMedicineDialog() {
        Dialog.Builder builder = new SimpleDialog.Builder(R.style.SimpleDialogLight) {
            @Override
            public void onPositiveActionClicked(DialogFragment fragment) {
                super.onPositiveActionClicked(fragment);
                oneMedicineInterface();
            }

            @Override
            public void onNegativeActionClicked(DialogFragment fragment) {
                super.onNegativeActionClicked(fragment);
            }
        };

        builder.title("确定药物已服用吗？")
                .positiveAction("确定")
                .negativeAction("取消");
        ((SimpleDialog.Builder) builder)
                .message("注：确认后您还可以到当天的用药记录里进行详细修改。");
        DialogFragment fragment = DialogFragment.newInstance(builder);

        if (this instanceof AppCompatActivity) {
            AppCompatActivity activity = this;
            fragment.show(activity.getSupportFragmentManager(), null);
        }
    }

    //服药接口调用
    public void oneMedicineInterface() {
        //默认从头部往下第三个开始获取DetailId()
        String id = remindMedicineAdapter.getData().get(remindMedicineAdapter.getData().size() - 2).getDetailId() + "";//药单id
        ViseLog.d("获取药单id+oneMedicineInterface" + remindMedicineAdapter.getData().get(remindMedicineAdapter.getData().size() - 2).getDetailId());
        remindMedicinePresenter.AddMutiTakeMedicineData(id);
    }

    //添加药品
    @OptionsItem(R.id.menu_addmedicine)
    public void menu_addmedicine() {
        String time = null;
        if (prescriptionDayData != null) {
            if (prescriptionDayData.getList() != null) {
                if (prescriptionDayData.getList().size()!= 0) {
                    time = prescriptionDayData.getList().get(0).getPrescriptionIndex();
                }
            }
        }

        if (time != null) {
            AddPrescriptionActivity_.intent(this).beanList(beanList).DataTime(time).start();
        } else {
            AddPrescriptionActivity_.intent(this).start();
        }
    }

    @Override
    public void onBackPressed() {
        ViseLog.d("发送通知更新界面");
        reshUi();
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    //刷新界面
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(UpdateEvent updateEvent) {
        if (updateEvent.type.equals(ConstantManger.MYGUESS)) {
            //查询当日服药单信息
            remindMedicinePresenter.GetPatientSingleDoseDetailData(TimeZoneUtil.sdf.format(new Date()));
            ViseLog.d("刷新home药单界面");
        }
    }

    @Click(R.id.iv_search_date)
    public void iv_search_date() {
        TakeMedicineActivity_.intent(this).start();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case android.R.id.home:
                ViseLog.d("点击了返回按钮");
                reshUi();
                break;
        }

        return super.onOptionsItemSelected(item);

    }

    //刷新界面
    public void reshUi(){
        UpdateEvent updateEvent = new UpdateEvent();
        updateEvent.type = ConstantManger.MYGUESS;
        EventBus.getDefault().post(updateEvent);
    }

    //历史药单信息
    @Override
    public void onSeccessHistory(PrescriptionDayData data) {

    }
    ArrayList<AllprescriptionDataBean> beanList = null;
    private PrescriptionDayData prescriptionDayData;
    //我的药单信息
    @Override
    public void onPrescriptionDaySuccess(PrescriptionDayData data) {
        beanList = new ArrayList<>();
        if (data.getList() != null) {
            prescriptionDayData = data;
        }

        int nums = data.getList().get(0).getPerscriptDetailList().size();
        for (int i = 0; i < nums; i++) {
            AllprescriptionDataBean allprescriptionDataBean = new AllprescriptionDataBean();
            allprescriptionDataBean.setPer_name(data.getList().get(0).getPerscriptDetailList().get(i).getMName()); //填充名称
            allprescriptionDataBean.setDoseName(data.getList().get(0).getPerscriptDetailList().get(i).getDoseName()); //填充规格
            allprescriptionDataBean.setPackages(data.getList().get(0).getPerscriptDetailList().get(i).getPackages()); //包装
            allprescriptionDataBean.setStartTime(data.getList().get(0).getPerscriptDetailList().get(i).getPeriodBegin()); //时间
            allprescriptionDataBean.setTimeLen(data.getList().get(0).getPerscriptDetailList().get(i).getTimeLen()); // TimeLen
            allprescriptionDataBean.setUseTypeId(data.getList().get(0).getPerscriptDetailList().get(i).getUseTypeId());//如何服药
            allprescriptionDataBean.setUserPeriodId(data.getList().get(0).getPerscriptDetailList().get(i).getUserPeriodId() + ""); //服药天数
            allprescriptionDataBean.setmID(data.getList().get(0).getPerscriptDetailList().get(i).getMid() + "");
            allprescriptionDataBean.setId(data.getList().get(0).getPerscriptDetailList().get(i).getId() + "");
            allprescriptionDataBean.setPlId(data.getList().get(0).getPerscriptDetailList().get(i).getPlId() + "");
            List<AllprescriptionDataBean.PrescriptionDoseDetailBean> mlist = new ArrayList<>();
            for (int a = 0; a < data.getList().get(0).getPerscriptDetailList().get(i).getPrescriptionDoseDetail().size(); a++) {
                AllprescriptionDataBean.PrescriptionDoseDetailBean prescriptionDoseDetailBean = new AllprescriptionDataBean.PrescriptionDoseDetailBean();
                prescriptionDoseDetailBean.setDetailId(data.getList().get(0).getPerscriptDetailList().get(i).getPrescriptionDoseDetail().get(a).getDetailId());
                prescriptionDoseDetailBean.setId(data.getList().get(0).getPerscriptDetailList().get(i).getPrescriptionDoseDetail().get(a).getId());
                prescriptionDoseDetailBean.setPlId(data.getList().get(0).getPerscriptDetailList().get(i).getPrescriptionDoseDetail().get(a).getPlId());
                prescriptionDoseDetailBean.setUseCount(data.getList().get(0).getPerscriptDetailList().get(i).getPrescriptionDoseDetail().get(a).getUseCount()+"");
                prescriptionDoseDetailBean.setUseTime(data.getList().get(0).getPerscriptDetailList().get(i).getPrescriptionDoseDetail().get(a).getUseTime());
                mlist.add(prescriptionDoseDetailBean);
            }
            allprescriptionDataBean.setPrescriptionDoseDetail(mlist);
            beanList.add(allprescriptionDataBean);
        }
    }
}
